package com.dlyk.aspect;

import com.dlyk.bean.TUser;
import com.dlyk.common.DataScope;
import com.dlyk.constant.Constants;
import com.dlyk.query.BaseQuery;
import com.dlyk.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;


/**
 * 切面
 */
@Aspect
@Component
public class DataScopeAspect {

    /**
     * 对注解进行切面：切入点
     */
    @Pointcut(value = "@annotation(com.dlyk.common.DataScope)")
    private void pointCut(){}

    /**
     * 连接点
     */
    @Around(value = "pointCut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        // 从连接点中提取方法签名信息
        MethodSignature methodSignature =(MethodSignature) joinPoint.getSignature();

        // 获取被拦截方法的对象,从对象中提取直接声明在方法上的注解
        DataScope dataScope = methodSignature.getMethod().getDeclaredAnnotation(DataScope.class);

        // 获取表的别名
        String tableAlias = dataScope.tableAlias();
        // 获取表的字段名
        String tableFiled = dataScope.tableFiled();

        // 获取请求
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取请求头信息
        String token = request.getHeader(Constants.TOKEN_NAME);

        // 密码解密
        TUser tUser = JWTUtils.parseUserFromJWT(token);

        // 获取用户角色
        List<String> roleList = tUser.getRoleList();

        // 对管理员角色进行判断
        if (!roleList.contains("admin")){
            Object params = joinPoint.getArgs()[0];
            if (params instanceof BaseQuery){
                BaseQuery query=(BaseQuery)params;
                query.setFilterSQL(" AND "+tableAlias+"."+tableFiled+" = "+tUser.getId());
            }
        }
        return joinPoint.proceed();
    }
}
